package util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DateUtil {

	/**
	 * 日期工具格式一，为"yyyy-MM-dd HH:mm:ss";
	 */
	public static final int formatCode1 = 1;
	/**
	 * 日期工具格式二，为"yyyy-MM-dd";
	 */
	public static final int formatCode2 = 2;

	private final static ThreadLocal<Map<Integer, DateFormat>> formatLocaLStore = new ThreadLocal<Map<Integer, DateFormat>>();

	private static DateFormat getDateFormat(int formatCode) {
		Map<Integer, DateFormat> formatLocal = formatLocaLStore.get();
		if (formatLocal == null) {
			formatLocal = new HashMap<Integer, DateFormat>();
			DateFormat format = createDateFormat(formatCode);
			formatLocal.put(1, format);
			return format;
		} else {
			DateFormat format = formatLocal.get(formatCode);
			if (formatLocal.get(formatCode) == null) {
				DateFormat format1 = createDateFormat(formatCode);
				formatLocal.put(1, format1);
				return format1;
			} else {
				return format;
			}
		}
	}

	private static DateFormat createDateFormat(int formatCode) {
		switch (formatCode) {
		case 1: {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}

		case 2: {
			return new SimpleDateFormat("yyyy-MM-dd");
		}
		default:
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
	}

	public static String getStringFromNowDate() {
		return getDateFormat(1).format(new Date());
	}

	public static String getStringFromNowDate(int formatCode) {
		return getDateFormat(formatCode).format(new Date());
	}

	public static String getStringFromDate(Date date) {
		if (date != null)
			return getDateFormat(1).format(date);
		return "";
	}

	public static String getStringFromDate(int formatCode, Date date) {
		if (date != null)
			return getDateFormat(formatCode).format(date);
		return "";
	}

	public static Date getDateFromString(String date) {
		if (date != null && !"".equals(date)) {
			try {
				return getDateFormat(1).parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static Date getDateFromString(int formatCode, String date) {
		if (date != null && !"".equals(date)) {
			try {
				return getDateFormat(formatCode).parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static long getLongFromString(String date) {
		return getDateFromString(date).getTime();
	}
}
